import Tab from "@src/components/tab";
import {Link, useNavigate} from "react-router-dom";
import {Formik} from 'formik';
import * as Yup from 'yup';
import EmailIcon from "@src/assets/e-mail.svg?react"
import PsdIcon from "@src/assets/psd.svg?react"
import {FormikProps} from "formik";
import VerificationCodeIcon from "@src/assets/verification-code.svg?react"
import FormInputIcon from "../_components/formInputIconProps"
import {useState} from "react";
import UserIcon from "@src/assets/user.svg?react";
import "./index.scss"
import {guestLogin, loginCode, loginSendCode, usersLogin, usersRegisterFromType} from "@src/services/userinfo.ts"
import HeadList from "@src/components/headList"
import VerifyCodeButton from "@src/pages/logIn/_components/verifyCodeButton";
import {useRequest} from "ahooks";
import toast from 'react-hot-toast';

export default function Register() {
    const navigate = useNavigate();
    const usersLoginApi = useRequest(usersLogin, {manual: true})
    const loginCodeApi = useRequest(loginCode, {manual: true})
    const guestLoginApi = useRequest(guestLogin, {manual: true})
    //存放 Tab 选择 下标
    const [activeIndex, setActiveIndex] = useState<number>(0);
    const onSubmit = (value: usersRegisterFromType) => {
        localStorage.removeItem("UserData")
        if (activeIndex == 1) {
            usersLoginApi.runAsync(value.email, value.password).then((result) => {
                localStorage.setItem("UserData", JSON.stringify(result.data));
                navigate("/home")
                toast("欢迎尊贵的" + result.data.user.name, {icon: "🫠"});
            })
        } else if (activeIndex == 2) {
            loginCodeApi.runAsync(value.email, value.verificationCode).then((result) => {
                localStorage.setItem("UserData", JSON.stringify(result.data));
                navigate("/home")
                toast("欢迎尊贵的" + result.data.user.name, {icon: "🫠"})
            })
        } else if (activeIndex == 0) {
            if (value.avatar == "") {
                toast("请重新选择头像", {icon: "🫠"})
            } else {
                guestLoginApi.runAsync(value.name, value.avatar).then((result) => {
                    localStorage.setItem("UserData", JSON.stringify(result.data))
                    navigate("/home")
                    toast("欢迎尊贵的" + result.data.user.name, {icon: "🫠"})
                })
            }
        }
    }
    const [initialValues, setInitialValues] = useState<usersRegisterFromType>({
        email: "",
        password: "",
        verificationCode: "",
        name: "游客" + Math.floor(Math.random() * 1000000),
        avatar: ""
    })
    const validationSchema = [Yup.object({
        name: Yup.string().required("昵称是必须的哦~").matches(/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, '不能包含特殊字符'),
    }), Yup.object({
        email: Yup.string().required('必填').email('无效的电子邮件地址').matches(/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, '无效的电子邮件地址'),
        password: Yup.string().required('必填'),
    }), Yup.object({
        email: Yup.string().required('必填').email('无效的电子邮件地址').matches(/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, '无效的电子邮件地址'),
        verificationCode: Yup.string().required('必填')
    })]


    return (
        <div className="card content">
            <div className="logo">欢迎登录</div>
            <Formik
                initialValues={initialValues}
                validationSchema={validationSchema[activeIndex]}
                onSubmit={onSubmit}
            >
                {formik => (
                    <form onSubmit={formik.handleSubmit}>
                        <div className="from">
                            <Tab tabs={[
                                {
                                    title: "游客进入", content: <Tourist formik={formik} onChange={(headUrl) => {
                                        formik.values.avatar = headUrl
                                        setInitialValues(formik.values)
                                    }}></Tourist>
                                },
                                {title: "账户登录", content: <AccountLogin formik={formik}/>},
                                {title: "验证码登录", content: <VerificationCodeLogin formik={formik}/>},
                            ]} onTabChange={(activeIndex) => {
                                setActiveIndex(activeIndex)
                                formik.resetForm()
                            }}/>
                        </div>
                        <div className="check-box">
                            <div>
                                {/*<input type="checkbox"/>*/}
                                {/*<span>记住我</span>*/}
                            </div>
                            <p><Link to="/logIn/resetPasswords">忘记密码?</Link></p>
                        </div>
                        <button type="submit" className="z-button"
                                disabled={guestLoginApi.loading}>{guestLoginApi.loading ? "正在登录~" : "登录"}
                        </button>
                    </form>
                )}
            </Formik>
            <p>还没有账户? <Link to="/logIn/enroll">立即注册</Link></p>

        </div>
    )
}

//游客登录
function Tourist({formik, onChange}: { formik: FormikProps<usersRegisterFromType>; onChange: (url: string) => void }) {
    const [url, setUrl] = useState<string>("#");

    return <div className="Tourist">
        <div>
            <img className="userHead" src={url} alt=""/>
        </div>
        <FormInputIcon
            Icon={<UserIcon/>}
            name="name"
            placeholder="请输入昵称"
            formik={formik}
        />
        <HeadList getHeadUrlData={(data) => {
            setUrl(data[0]);
            onChange(data[0])
        }}
                  onChange={(url) => {
                      setUrl(url);
                      onChange(url)
                  }}>
        </HeadList>
    </div>
}

//账户登录
function AccountLogin({formik}: { formik: FormikProps<usersRegisterFromType> }) {
    return (
        <div className="account-login">
            <FormInputIcon
                Icon={<EmailIcon/>}
                name="email"
                placeholder="请输入邮箱"
                type="email"
                formik={formik}
            />

            <FormInputIcon
                Icon={<PsdIcon/>}
                name="password"
                placeholder="请输入密码"
                type="password"
                formik={formik}
            />
        </div>
    )
}

//验证码登录
function VerificationCodeLogin({formik}: { formik: FormikProps<usersRegisterFromType> }) {
    const [disabled, setDisabled] = useState(false);
    const loginSendCodeApi = useRequest(loginSendCode, {manual: true});
    return (
        <div className="verificationCodeLogin">

            <FormInputIcon
                Icon={<EmailIcon/>}
                name="email"
                placeholder="请输入邮箱"
                type="email"
                formik={formik}
            />

            <div className="verification-code">
                <FormInputIcon
                    Icon={<VerificationCodeIcon/>}
                    name="verificationCode"
                    placeholder="请输入验证码"
                    formik={formik}
                />
                <VerifyCodeButton onGetCode={() => {
                    formik.setFieldTouched("email", true).then((value) => {
                        if (value?.email == undefined) {
                            loginSendCodeApi.runAsync(formik.values.email).then(() => {
                                toast.success("验证码已发送")
                                setDisabled(true)
                            })
                        }
                    })
                }} disabled={disabled} setDisabled={setDisabled}></VerifyCodeButton>
            </div>

        </div>
    )
}

